package cn.itsource.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import cn.itsource.constant.SystemConstant;
import cn.itsource.domain.Course;
import cn.itsource.query.CourseQuery;
import cn.itsource.service.ICourseService;
import cn.itsource.util.AjaxResult;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 接口类：课程Course
 */
@RestController
@RequestMapping("/course")
@Api(value = "课程接口类", description = "处理课程的所有请求")
public class CourseController {

    @Autowired
    private ICourseService courseService;


    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询所有数据")
    public List<Course> list() {
        return courseService.findAll();
    }


    /**
     * 查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个数据")
    public Course findOne(@PathVariable("id") Long id) {
        return courseService.findOne(id);
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单个数据")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            courseService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }


    /**
     * 添加和修改
     * @param articleType
     * @return
     */
    @PutMapping
    @ApiOperation(value = "添加或修改")
    public AjaxResult addOrUpdate(@RequestBody Course course) {
        try {
            if (course.getId() == null) {//添加
                courseService.add(course);
            } else {
                courseService.update(course);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }


    /**
     * 分页查询 + 高级查询
     * @param query
     * @return
     */
    @PostMapping
    @ApiOperation(value = "分页查询或高级查询")
    public PageInfo<Course> pageQuery(@RequestBody CourseQuery query) {
        return courseService.pageQuery(query);
    }


    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除")
    public AjaxResult patchDel(@RequestBody Long[] ids) {
        try {
            courseService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络繁忙,请稍后重试");
        }
    }


    /**
     * 后台首页 - 导出所有数据
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportData")
    @ApiOperation(value = "后台首页 - 导出所有数据")
    public void exportData(HttpServletResponse response) throws IOException {
        List<Course> courses = courseService.findAll();
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //写出数据：先写出，然后调整自适应宽度才有效
        writer.write(courses, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + SystemConstant.EXCEL_NAME);
        ServletOutputStream out = response.getOutputStream();

        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }


    /**
     * 后台首页 - 导入数据
     * @param file
     * @throws IOException
     */
    @PostMapping("/importData")
    @ApiOperation(value = "后台首页 - 导入数据")
    public void importData(@RequestPart("file") MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Course> courses = reader.readAll(Course.class);
        if (courses != null && courses.size() > 0) {
            courseService.patchAdd(courses);
        }
    }


    /**
     * 设置基础字体样式
     *
     * @param writer
     * @param bold     是否粗体
     * @param italic
     * @param fontName 字体名称
     * @param fontSize 字体大小
     * @return
     */
    public Font createFont(ExcelWriter writer, boolean bold, boolean italic, String fontName, int fontSize) {
        Font font = writer.getWorkbook().createFont();
        //设置字体名称 宋体 / 微软雅黑 /等
        font.setFontName(fontName);
        //设置是否斜体
        font.setItalic(italic);
        //设置字体大小 以磅为单位
        font.setFontHeightInPoints((short) fontSize);
        //设置是否加粗
        font.setBold(bold);
        return font;
    }

    /**
     * 方法描述: 全局基础样式设置
     * 默认 全局水平居中+垂直居中
     * 默认 自动换行
     * 默认单元格边框颜色为黑色，细线条
     * 默认背景颜色为白色
     */
    public StyleSet setBaseGlobalStyle(ExcelWriter writer, Font font) {
        //全局样式设置
        StyleSet styleSet = writer.getStyleSet();
        //设置全局文本垂直方向局居中，水平放行居左
        styleSet.setAlign(HorizontalAlignment.LEFT, VerticalAlignment.CENTER);
        //设置全局字体样式
        styleSet.setFont(font, true);
        //设置背景颜色 第二个参数表示是否将样式应用到头部
        styleSet.setBackgroundColor(IndexedColors.WHITE, true);
        //设置自动换行 当文本长于单元格宽度是否换行
        styleSet.setWrapText();
        // 设置全局边框样式
        //styleSet.setBorder(BorderStyle.THIN, IndexedColors.GREY_25_PERCENT);
        return styleSet;
    }

}
